<template>
  <div class="el-dialog-select el-select" :class="[selectSize ? 'el-select--' + selectSize : '']">
    <el-input
      type="text"
      v-model="selectedLabel"
      :size="selectSize"
      readonly
      :clearable="clearable"
      :placeholder="placeholder"
      @focus="handleFocus"
      @mouseenter.native="inputHovering = true"
      @mouseleave.native="inputHovering = false">
      <template slot="suffix">
        <i v-if="!showClose" class="el-select__caret el-input__icon el-icon-arrow-up"></i>
        <i v-if="showClose" class="el-select__caret el-input__icon el-icon-circle-close" @click="handleClearClick"></i>
      </template>
    </el-input>

    <!-- Dialog -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      @open="handleOpen"
      custom-class="el-select-dialog"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false">

      <slot name="filter"></slot>
      <el-table
        ref="selectTable"
        size="medium"
        :data="tableData"
        border
        :highlight-current-row="!multiple"
        @current-change="handleCurrentChange"
        @selection-change="handleSelectionChange"
        style="width: 100%">
        <el-table-column v-if="multiple" type="selection" width="50"></el-table-column>
        <el-table-column v-for="(column, index) in typeConfig.showColumns" :key="index" :label="column.title" :prop="column.code" :formatter="column.formatter" :width="column.width"></el-table-column>
      </el-table>

      <template v-slot:footer>
        <div class="select-dialog-footer">
          <div class="select-pagination">
            <el-pagination
              background
              :current-page.sync="pageDesc.pageNum"
              :page-size="pageDesc.pageSize"
              :total="total"
              @current-change="getTableData"
              layout="prev, pager, next">
            </el-pagination>
          </div>
          <div>
            <el-button size="medium" @click="handleClose">取 消</el-button>
            <el-button size="medium" type="primary" :disabled="!canSubmit" @click="handleSelectConfirm">确 定</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { queryDatasByIds, page } from "@/api/lc/bizData";
import {getInfoByCode} from "@/api/lc/biz"
export default {
  inject: {
    elForm: { default: '' },
    elFormItem: { default: '' }
  },
  async mounted() {
   await this.initTypeConfig()
   this.initSelectValue()
  },

  watch: {
    value (newVal, oldVal)   {
      this.initSelectValue ()
    },
  },
  computed: {
    _elFormItemSize () {
      return (this.elFormItem || {}).elFormItemSize
    },
    selectSize () {
      return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size
    },
    selectedLabel () {
      if(this.selectValue != null) {
        if (this.multiple) {
          return this.selectValue.map(item => item[this.option.label]).join('，')
        } else {
          return this.selectValue[this.option.label]
        }
      } else {
        return this.placeholder
      }

    },
    showClose () {
      const hasValue = this.multiple
        ? Array.isArray(this.selectValue) && this.selectValue.length > 0
        : this.selectValue && Object.prototype.hasOwnProperty.call(this.selectValue, this.option.value)
      const criteria = this.clearable && this.inputHovering && hasValue
      return criteria
    },
    canSubmit () {
      if (this.multiple) {
        return this.currentSelectedGroup.length || this.selectedGroup.length
      } else {
        return this.selectRow && Object.prototype.hasOwnProperty.call(this.selectRow, this.option.value)
      }
    }
  },
  props: {
    size: String,
    bizType: String, //业务类型
    multiple: { type: Boolean, default: false },
    clearable: { type: Boolean, default: false },
    value: { type: String, required: false },
    placeholder: { type: String, default: '请选择' },
    title: { type: String, default: '请选择' },
    request: { type: Function, required: true },
    filter: Object,
    multipleSort: Function
  },
  data () {
    return {
      selectValue:null,
      inputHovering: false,
      dialogVisible: false,
      pageDesc: { pageNum: 1, pageSize: 10 },
      tableData: [],
      total: 0,
      selectRow: this.multiple ? [] : null, // 选中结果
      currentSelectedGroup: [], // 多选当前Page选中项
      selectedGroup: [], // 多选除当前Page外的其他选中项（跨页数据）
      option: { label: 'title', value: 'code' },
      typeConfig:{
        code: null,
        title: null,
        componentUrl: null,
        masterTableName: null,
        workflowDefineId: null,
        showColumns: [
          { code: 'code', title : '代码' },
          { code: 'title', title: '名称'}]
      }
    }
  },
  methods: {
    async initTypeConfig() {
      await getInfoByCode(this.bizType).then(response => {
        this.typeConfig = response.data
        this.typeConfig.showColumns = JSON.parse(this.typeConfig.showColumns)
        this.option = { label: this.typeConfig.showProps, value: this.typeConfig.idProps }
        console.log(this.option)
      })
    },
    async initSelectValue () {
      if(this.value && this.value != null && this.value.length > 0)  {
        queryDatasByIds(this.bizType, this.value).then(response => {
          if(this.multiple) {
            this.selectValue = response.data
          } else {
            this.selectValue = response.data && response.data.length>0 ? response.data[0] : null
          }
        })
      } else {
        if(this.multiple) {
          this.selectValue = null
        } else {
          this.selectValue = null
        }
      }
    },
    handleFocus () {
      this.dialogVisible = true
    },
    handleClearClick () {
      if (this.multiple) {
        this.$emit('input', [])
      } else {
        this.$emit('input', {})
      }
    },
    handleOpen () {
      if (this.multiple) {
        this.selectedGroup = this.selectValue
      }
      this.getTableData()
    },
    getTableData (pageNum = 1) {
      this.pageDesc.pageNum = pageNum
      if (this.multiple) {
        this.selectedGroup.push(...this.currentSelectedGroup)
      } else {
        this.selectRow = null
      }
      const params = Object.assign({}, this.pageDesc, this.filter)
      params.type = this.typeConfig.code
      page(params).then(resp => {
        resp = resp.data
        this.tableData = resp.records
        this.total = resp.total
        // 数据反显 行选中状态
        this.$nextTick(() => {
          if (this.multiple) {
            const otherSelectRows = []
            this.selectedGroup.forEach(row => {
              const hasRow = this.tableData.find(item => item[this.option.value] === row[this.option.value])
              if (hasRow) {
                this.$refs.selectTable.toggleRowSelection(hasRow, true)
              } else {
                otherSelectRows.push(row)
              }
            })
            this.selectedGroup = otherSelectRows
          } else {
            if (this.selectValue && Object.prototype.hasOwnProperty.call(this.selectValue, this.option.value)) {
              const hasRow = this.tableData.find(item => this.selectValue[this.option.value] === item[this.option.value])
              if (hasRow) {
                this.selectRow = hasRow
                this.$refs.selectTable.setCurrentRow(hasRow)
              }
            }
          }
        })
      })
    },
    // 单选选中行
    handleCurrentChange (currentRow) {
      if (this.multiple) return
      this.selectRow = currentRow
    },
    handleSelectionChange (selection) {
      this.currentSelectedGroup = selection
    },
    handleSelectConfirm () {
      if (this.multiple) {
        const res = []
        res.push(...this.selectedGroup, ...this.currentSelectedGroup)
        this.selectRow = res
        this.multipleSort && this.selectRow.sort(this.multipleSort)
        this.$emit('input', this.selectRow.map(item => item[this.option.value]).join('，'))
      } else {
        this.$emit('input', this.selectRow[this.option.value])
      }
      this.handleClose()
    },
    handleClose () {
      this.dialogVisible = false
      this.pageDesc = { pageNum: 1, pageSize: 10 }
      this.tableData = []
      this.total = 0
      this.selectRow = this.multiple ? [] : null
      this.currentSelectedGroup = []
      this.selectedGroup = []
    }
  }
}
</script>

<style lang="scss">
.el-dialog.el-select-dialog {
  width: 70%;
  max-height: 70%;
  display: flex;
  flex-direction: column;
  .el-dialog__body {
    padding: 10px 20px;
    flex: 1;
    overflow: auto;
    // 表格错位
    .el-table th.gutter {
      display: table-cell !important;
    }
    .el-table colgroup.gutter {
      display: table-cell !important;
    }
    .el-table__body tr.current-row > td {
      background-color: #cbe4ff;
    }
  }
  .select-dialog-footer {
    display: flex;
    justify-content: space-between;
    .select-pagination {
      display: flex;
      align-items: center;
      .el-pagination {
        padding-left: 0;
        margin-left: -5px;
      }
    }
  }
}
</style>
